/**
 * 
 */
package mdb.com.vn.web.beans;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.xml.rpc.ServiceException;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import mdb.com.vn.model.Casa;
import mdb.com.vn.model.FixedDepositCasa;
import mdb.com.vn.model.LuckyDraw;
import mdb.com.vn.model.ScratchCard;
import mdb.com.vn.services.MDBServices;
import mdb.com.vn.utils.DateUtils;
import mdb.com.vn.utils.NumberUtils;
import mdb.com.vn.web.utils.FacesContextUtils;
import mdb.com.vn.wservices.utils.CasaFromT24;
import mdb.com.vn.wservices.utils.WSUtils;

/**
 * @author tu.dod
 * 
 */
@ManagedBean(name = "processCSBeans")
@ViewScoped
public class ProcessCSBeans implements Serializable {

	private static final long serialVersionUID = 1L;
	private String accountLockedNo;
	
	private int number00k;
	private int number20k;
	private int number50k;
	private int number100k;
	private int number200k;
	private int number500k;

	private String detail20k;
	private String detail50k;
	private String detail100k;
	private String detail200k;
	private String detail500k;
	private boolean btnVisible;
	private boolean btnSaveVisible;
	private boolean componentVisible;
	private int totalScradAvailable;

	private Casa casa;
	private StreamedContent file;

	@ManagedProperty("#{mdbServices}")
	private MDBServices mdbServices;

	@PostConstruct
	public void init() {
		accountLockedNo = "";
		casa = new Casa();
		// casa.setCheckGetThankSC(true);
	}

	public void searchCasafromT24P() throws Exception {
		try {
			casa = new Casa();
			if (accountLockedNo.equals("")) {
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_WARN,
								"Nhập số sổ tiết kiệm không kỳ hạn là thông tin bắt buộc!",
								"Vui lòng nhập lại"));
			} else {
				if (accountLockedNo.substring(0, 1).equals("2")
						&& accountLockedNo.length() == 11) {
					Casa casachecked = mdbServices
							.findCasaByCode(accountLockedNo);
					
					FixedDepositCasa depositCasa = mdbServices
							.findFixedDepositCasaByCodeCS(accountLockedNo);
					if (casachecked != null || depositCasa != null) {
						casa.setLuckyDraw(0);
						casa.setScCard(0);
						setBtnSaveVisible(false);
						setComponentVisible(false);
						FacesContext
								.getCurrentInstance()
								.addMessage(
										null,
										new FacesMessage(
												FacesMessage.SEVERITY_WARN,
												"Tài khoản này đã tham chương trình khuyến mãi rồi ",
												"Vui lòng xem lại thể lệ chương trình"));
					} else {
						casa = CasaFromT24
								.getCasaFromT24(casa, accountLockedNo);

						Date startDate = casa.getOpeningDate();
						Date promotion = DateUtils
								.createDateYYYYMMDD("20131209");

						if (casa.getWbBalances() < 10000000
								|| casa.getInterestRate() != 0.5
								|| !casa.getCategory().equals("6001")
								|| startDate.compareTo(promotion) < 0) {
							setBtnSaveVisible(false);
							setComponentVisible(false);
							FacesContext
									.getCurrentInstance()
									.addMessage(
											null,
											new FacesMessage(
													FacesMessage.SEVERITY_WARN,
													"Tài khoản không tồn tại hoặc không đủ điều kiện tham gia chương trình khuyến mãi! ",
													"Vui lòng kiểm tra lại hoặc xem thể lệ chương trình"));
						} else {
							casa.setAmountLocked(new BigDecimal(casa
									.getWbBalances()));
							casa.setDateLocked(casa.getOpeningDate());
							if (casa.getCustomerType() == 1) {
								setTotalScradAvailable(mdbServices
										.getSCardFDAvailable(casa
												.getCustomerId())
										+ mdbServices.getSCardCSAvailable(casa
												.getCustomerId())
										+ mdbServices
												.getSCardFDCSAvailable(casa
														.getCustomerId()));
								int tocalculatebag = casa.getScCard()
										+ getTotalScradAvailable();
								casa.setBagGift(tocalculatebag / 5);
								casa.setTrayGift(tocalculatebag / 10);
							}
							setBtnSaveVisible(true);
							setComponentVisible(true);
						}
					}
				} else {
					setBtnSaveVisible(false);
					setComponentVisible(false);
					FacesContext
							.getCurrentInstance()
							.addMessage(
									null,
									new FacesMessage(
											FacesMessage.SEVERITY_WARN,
											"Không đúng định dạng của số Sổ tiết kiệm ",
											"Vui lòng nhập lại 11 chữ số và chữ số đầu tiên là 2"));
				}
			}

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		}

	}

	public void calculateCasa() throws Exception {
		if (casa.getAmountLocked() == null || casa.getDateLocked() == null
				|| casa.getTermLocked() == 0) {
			setBtnSaveVisible(true);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN,
							"Nhập đầy đủ thông tin khách hàng cam kết",
							"Vui lòng nhập lại"));

		} else {

			if (casa.getAmountLocked().compareTo(
					new BigDecimal(casa.getWbBalances())) <= 0
					&& casa.getDateLocked().compareTo(
							DateUtils.getOnlyDDMMYYYY(casa.getOpeningDate())) >= 0
					&& casa.getTermLocked() >= 38) {

				if (casa.getCustomerType() == 1) {
					casa.setLuckyDraw(WSUtils.CalculateLDRCasa(
							casa.getTermLocked(), casa.getInterestRate(),
							new BigDecimal(casa.getWbBalances())));
					casa.setScCard(WSUtils.CalculateLDRCasa(
							casa.getTermLocked(), casa.getInterestRate(),
							new BigDecimal(casa.getWbBalances())));
					casa.setBagGift(WSUtils.CalculateGiftBag(casa
							.getLuckyDraw()));
					casa.setTrayGift(WSUtils.CalculateGiftTray(casa
							.getLuckyDraw()));
					casa.setEndDateLocked(DateUtils.dateInfuture(casa.getOpeningDate(),
							casa.getTermLocked()));

					setTotalScradAvailable(mdbServices.getSCardFDAvailable(casa
							.getCustomerId())
							+ mdbServices.getSCardCSAvailable(casa
									.getCustomerId())
							+ mdbServices.getSCardFDCSAvailable(casa
									.getCustomerId()));
					int tocalculatebag = casa.getScCard()
							+ getTotalScradAvailable();
					casa.setBagGift(tocalculatebag / 5);
					casa.setTrayGift(tocalculatebag / 10);
				}

			} else {
				setBtnSaveVisible(true);
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_WARN,
								"Thông tin khách hàng cam kết không hợp lệ ",
								"Vui lòng nhập lại"));

			}

		}

	}

	public void addNewCasaP() {
		int total_sc = number00k + number20k + number50k + number100k + number200k
				+ number500k;
		int total_sc_full = casa.getScCard() + getTotalScradAvailable();
		int bagReceived = casa.getBgiftReceived();
		int trayReceived = casa.getTgiftReceived();

		bagReceived = bagReceived * 5;
		trayReceived = trayReceived * 10;
		int total_sc_received = bagReceived + trayReceived;

		if (total_sc > casa.getScCard() || total_sc_received > total_sc_full) {
			setBtnSaveVisible(true);
			FacesContext
					.getCurrentInstance()
					.addMessage(
							null,
							new FacesMessage(
									FacesMessage.SEVERITY_WARN,
									"Vượt quá số lượng áo thun, khay mứt và thẻ cào cho phép ",
									"Vui lòng nhập lại"));
		} else {

			if (total_sc == casa.getScCard()) {
				try {
					casa.setScCardNotGet(casa.getScCard() - total_sc_received);
					mdbServices.addCasa(casa);
					for (int i = 0; i < casa.getLuckyDraw(); i++) {
						LuckyDraw luckyDraw = new LuckyDraw();
						luckyDraw.setCustomerRef(casa.getCustomerId());
						luckyDraw.setTransRef(casa.getAccountLocked());
						luckyDraw
								.setLdrDesription("Số dự thưởng cho "
										+ casa.getCustomerName());
						luckyDraw.setStatus(1);
						luckyDraw.setCreatedBy(casa.getCreatedBy());
						luckyDraw.setDateCreated(new Date());
						mdbServices.addLuckyDraw(luckyDraw);
					}
					if (number20k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(casa.getAccountLocked());
						scratchCard.setCreatedBy(casa.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail20k);
						scratchCard.setCustomerRef(casa.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(20000);
						scratchCard.setQuantity(number20k);
						mdbServices.addScratchCard(scratchCard);
					}
					if (number50k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(casa.getAccountLocked());
						scratchCard.setCreatedBy(casa.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail50k);
						scratchCard.setCustomerRef(casa.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(50000);
						scratchCard.setQuantity(number50k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number100k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(casa.getAccountLocked());
						scratchCard.setCreatedBy(casa.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail100k);
						scratchCard.setCustomerRef(casa.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(100000);
						scratchCard.setQuantity(number100k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number200k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(casa.getAccountLocked());
						scratchCard.setCreatedBy(casa.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail200k);
						scratchCard.setCustomerRef(casa.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(200000);
						scratchCard.setQuantity(number200k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number500k > 0) {
						ScratchCard scratchCard = new ScratchCard();
						scratchCard.setTransRef(casa.getAccountLocked());
						scratchCard.setCreatedBy(casa.getCreatedBy());
						scratchCard.setDateCreated(new Date());
						scratchCard.setScDesription(detail500k);
						scratchCard.setCustomerRef(casa.getCustomerId());
						scratchCard.setStatus(1);
						scratchCard.setScDenomination(500000);
						scratchCard.setQuantity(number500k);
						mdbServices.addScratchCard(scratchCard);

					}
					if (number00k > 0){
						casa.setCheckGetThankSC(number00k);
					}
					// /////////////////////////
					String fileName = casa.getAccountLocked() + ".pdf";
					Map<String, Object> data = new HashMap<String, Object>();

					data.put("BranchID", casa.getBranchCode());
					data.put("CustomerID", casa.getCustomerId());
					data.put("CustomerName", casa.getCustomerName());
					data.put("SavingBookNo", casa.getAccountLocked());

					data.put("CasaAmount", NumberUtils.format(
							casa.getWbBalances(), "###,###,###,###"));
					data.put("CasaTerm", casa.getTermLocked());

					data.put("TotalSCard", casa.getScCard());
					data.put("TotalLDR", casa.getLuckyDraw());

					data.put("BranchName", mdbServices
							.getCompanyNameByCode(casa.getBranchCode()));
					data.put(
							"LuckyDrawCodes",
							mdbServices.getAllLuckyDrawCodeP(
									casa.getAccountLocked(), 0));
					data.put("DateExpired",DateUtils.format(casa.getEndDateLocked(), "dd/MM/yyyy") );

					List<ScratchCard> scratchCards = mdbServices
							.getScratchCardByRef(casa.getAccountLocked());

					double totalSCAmount = 0;
					for (ScratchCard scratchCard : scratchCards) {
						if (scratchCard.getScDenomination() == 20000) {
							data.put("Card20k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 20000;
						}
						if (scratchCard.getScDenomination() == 50000) {
							data.put("Card50k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 50000;
						}
						if (scratchCard.getScDenomination() == 100000) {
							data.put("Card100k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 100000;
						}
						if (scratchCard.getScDenomination() == 200000) {
							data.put("Card200k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 200000;
						}
						if (scratchCard.getScDenomination() == 500000) {
							data.put("Card500k", scratchCard.getQuantity());
							totalSCAmount += scratchCard.getQuantity() * 500000;
						}
					}
					data.put("TotalSCAmount", NumberUtils.format(totalSCAmount,
							"###,###,###,###"));
					data.put(
							"ImagesPath",
							FacesContextUtils
									.getResourcePath("/WEB-INF/classes/mdb/com/vn/web/reports/MDB.jpg"));
						
					Casa casa2update = mdbServices.findCasaByCode(casa
							.getAccountLocked());

					if (casa.getCustomerType() == 1) {
						casa.setId(casa2update.getId());
						data.put("ThanksCard", casa.getCheckGetThankSC());
						data.put("TshirtGift", casa.getBgiftReceived());
						data.put("TrayGift", casa.getTgiftReceived());
						casa.setScCardAmt(totalSCAmount);	
						mdbServices.updateCasa(casa);

						JasperReport jasperReport = JasperCompileManager
								.compileReport(FacesContextUtils
										.getResourcePath("/WEB-INF/classes/mdb/com/vn/web/reports/CASAReport.jrxml"));

						JasperPrint jasperPrint = JasperFillManager.fillReport(
								jasperReport, data, new JREmptyDataSource());

						JasperExportManager.exportReportToPdfFile(jasperPrint,
								fileName);
					}
					File filetemps = new File(fileName);
					InputStream fis = new FileInputStream(filetemps);
					file = new DefaultStreamedContent(fis, "application/pdf",
							fileName);
					filetemps = new File(filetemps.getCanonicalPath());
					filetemps.delete();
					setBtnVisible(true);
					setBtnSaveVisible(false);
					setComponentVisible(false);
					FacesContext.getCurrentInstance().addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_INFO,
									"Lưu thông tin thành công",
									"Bấm nút 'In phiếu thông tin' để in phiếu thông tin cho khách hàng"));

				} catch (Exception e) {
					setBtnSaveVisible(true);
					FacesContext.getCurrentInstance().addMessage(
							null,
							new FacesMessage(FacesMessage.SEVERITY_ERROR,
									"Lỗi xảy ra trong qua trình thao tác",
									"Vui lòng kiểm tra lại"));
					e.printStackTrace();
				}
			} else {
				setBtnSaveVisible(true);
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_WARN,
								"Nhập chưa đầy đủ số lượng thẻ cào",
								"Vui lòng kiểm tra lại"));

			}

		}
	}

	public void downloadPrevented() {
		setBtnVisible(true);
		file = null;
	}

	public String getAccountLockedNo() {
		return accountLockedNo;
	}

	public void setAccountLockedNo(String accountLockedNo) {
		this.accountLockedNo = accountLockedNo;
	}

	public int getNumber20k() {
		return number20k;
	}

	public void setNumber20k(int number20k) {
		this.number20k = number20k;
	}

	public int getNumber50k() {
		return number50k;
	}

	public void setNumber50k(int number50k) {
		this.number50k = number50k;
	}

	public int getNumber100k() {
		return number100k;
	}

	public void setNumber100k(int number100k) {
		this.number100k = number100k;
	}

	public int getNumber200k() {
		return number200k;
	}

	public void setNumber200k(int number200k) {
		this.number200k = number200k;
	}

	public int getNumber500k() {
		return number500k;
	}

	public void setNumber500k(int number500k) {
		this.number500k = number500k;
	}

	public String getDetail20k() {
		return detail20k;
	}

	public void setDetail20k(String detail20k) {
		this.detail20k = detail20k;
	}

	public String getDetail50k() {
		return detail50k;
	}

	public void setDetail50k(String detail50k) {
		this.detail50k = detail50k;
	}

	public String getDetail100k() {
		return detail100k;
	}

	public void setDetail100k(String detail100k) {
		this.detail100k = detail100k;
	}

	public String getDetail200k() {
		return detail200k;
	}

	public void setDetail200k(String detail200k) {
		this.detail200k = detail200k;
	}

	public String getDetail500k() {
		return detail500k;
	}

	public void setDetail500k(String detail500k) {
		this.detail500k = detail500k;
	}

	public boolean isBtnVisible() {
		return btnVisible;
	}

	public void setBtnVisible(boolean btnVisible) {
		this.btnVisible = btnVisible;
	}

	public boolean isBtnSaveVisible() {
		return btnSaveVisible;
	}

	public void setBtnSaveVisible(boolean btnSaveVisible) {
		this.btnSaveVisible = btnSaveVisible;
	}

	public Casa getCasa() {
		return casa;
	}

	public void setCasa(Casa casa) {
		this.casa = casa;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setMdbServices(MDBServices mdbServices) {
		this.mdbServices = mdbServices;
	}

	public boolean isComponentVisible() {
		return componentVisible;
	}

	public void setComponentVisible(boolean componentVisible) {
		this.componentVisible = componentVisible;
	}

	public int getTotalScradAvailable() {
		return totalScradAvailable;
	}

	public void setTotalScradAvailable(int totalScradAvailable) {
		this.totalScradAvailable = totalScradAvailable;
	}

	public int getNumber00k() {
		return number00k;
	}

	public void setNumber00k(int number00k) {
		this.number00k = number00k;
	}
	
	
	

}
